package com.terry.server;

import com.terry.handler.HttpServerHandler;
import com.terry.interfaces.Contant;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpRequestDecoder;

public class NettyServer {

	private int port;
	
	public static void main(String[] args) {
//		init(args);
		int port = Contant.SERVER_PORT;
		new NettyServer(port).run();
	}
	
	public NettyServer(int port) {
		System.out.println("listen on: " + port);
		this.port = port;
	}
	
	public void run() {
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		try {
			ServerBootstrap bootstrap = new ServerBootstrap();
			bootstrap.group(bossGroup, workerGroup)
			.channel(NioServerSocketChannel.class)
			.childHandler(new ChannelInitializer<SocketChannel>() {
				@Override
				protected void initChannel(SocketChannel ch) throws Exception {
//					ch.pipeline().addLast(new MessageCoder());
//					ch.pipeline().addLast(new ServerHandler());
					//http request process
					ch.pipeline().addLast(new HttpRequestDecoder());
//					ch.pipeline().addLast(new ChunkedWriteHandler());
//					ch.pipeline().addLast(new HttpResponseDecoder());
					ch.pipeline().addLast(new HttpServerHandler());
				}
			})
			.option(ChannelOption.SO_BACKLOG, 128)
			.childOption(ChannelOption.SO_KEEPALIVE, true);
			ChannelFuture f = bootstrap.bind(this.port).sync();
			f.channel().closeFuture().sync();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}
	private static void init(String[] args) {
		if (args.length != 4) {
			System.out.println("Useage: local_host, local_port, target_host, target_port !");
			System.exit(0);
		}
		Contant.SERVER_HOST = args[0];
		Contant.SERVER_PORT = Integer.parseInt(args[1]);
		Contant.TARGET_HOST = args[2];
		Contant.TARGET_PORT = Integer.parseInt(args[3]);
		System.out.println("local_host: " + Contant.SERVER_HOST);
		System.out.println("local_port: " + Contant.SERVER_PORT);
		System.out.println("target_host: " + Contant.TARGET_HOST);
		System.out.println("target_port: " + Contant.TARGET_PORT);
	}

}
